package com.hc.core.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class UrlTool {
	/**
	 * 获得HttpURLConnection
	 * 
	 * @param url
	 * @return
	 * @throws IOException
	 * @throws MalformedURLException
	 */
	public static HttpURLConnection getHttpURLConnection(String url)
			throws MalformedURLException, IOException {
		return (HttpURLConnection) new URL(url).openConnection();
	}

	/**
	 * 关闭HttpURLConnection
	 * 
	 * @param conn
	 */
	public static void closeHttpURLConnection(HttpURLConnection conn) {
		conn.disconnect();
	}

	/**
	 * 获取請求url响应的内容
	 * 
	 * @return
	 */
	public static String getResponseContentFromRequestUrl(String url,
			String encoding) {
		StringBuffer responseContent = new StringBuffer();
		HttpURLConnection conn = null;
		try {
			// 1.获得连接
			conn = getHttpURLConnection(url);
			conn.connect();
			// 2.获取respnseContent
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					conn.getInputStream(), encoding));
			String line = null;
			while ((line = reader.readLine()) != null) {
				responseContent.append(line);
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			closeHttpURLConnection(conn);
		}

		return responseContent.toString();
	}

	public static void main(String[] arg) {
		String requestUrl = "http://211.68.122.164/webapps/bb-silkIII-bb_bb60/datas/course_visit.jsp";
		System.out.println(UrlTool.getResponseContentFromRequestUrl(requestUrl,
				"UTF-8"));
	}
}
